package com.filetransfer.view.Panel;
import com.filetransfer.api.ApiHelper;
import com.filetransfer.api.generated.MessageControllerApi;
import com.filetransfer.config.UserThemeConfiguration;
import com.filetransfer.controller.FileTransferController;
import com.filetransfer.view.Components.MessageInputDialog;
import com.filetransfer.view.Components.TaskPanel;
import com.filetransfer.view.Components.UploadHistorySelectionDialog;
import com.filetransfer.viewmodel.UploadTableRowViewModel;
import com.filetransfer.viewmodel.UploadTableViewModel;
import de.exlll.configlib.YamlConfigurations;
import lombok.extern.slf4j.Slf4j;
import raven.toast.Notifications;

import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.filetransfer.Main.CONFIG_FILE_PATH;
@Slf4j
public class UploadPanel extends TaskPanel<UploadTableViewModel, UploadTableRowViewModel> {
    private final FileTransferController controller;
    public UploadPanel(FileTransferController controller) {
        super("暂时无文件上传", "icons/cloud_upload.svg", new UploadTableViewModel());
        this.controller = controller;
        loadUploadHistory();
        setOptionalButtonVisible(true);
    }
    @Override
    protected void onActionButtonClick() {
        var window = SwingUtilities.getWindowAncestor(this);
        var taskName = "上传任务 " + (getTaskTable().getRowCount() + 1);
        if (window instanceof JFrame frame) {
            SwingWorker<Void, Integer> worker = new SwingWorker<>() {
                String fileName;
                String filePath;
                @Override
                protected Void doInBackground() {
                    var rowViewModel = new UploadTableRowViewModel(taskName, "初始化中", 0, "", "");
                    var shareResult = controller.chooseFile(frame, (file, index, length) -> {
                        addTask(rowViewModel);
                        rowViewModel.setStatus("上传中");
                        getMessageLabel().setText("上传中...");
                    }, (file, index, length) -> {
                        fileName = file.getName();
                        filePath = file.getPath();
                        rowViewModel.setStatus("完成");
                        getMessageLabel().setText("上传完成！");
                        Notifications.getInstance().show(
                                Notifications.Type.SUCCESS,
                                Notifications.Location.BOTTOM_LEFT,
                                "上传成功！文件已完成上传！"
                        );
                    }, () -> {
                        rowViewModel.setStatus("上传失败");
                        rowViewModel.setProgress(0);
                        Notifications.getInstance().show(
                                Notifications.Type.ERROR,
                                Notifications.Location.BOTTOM_LEFT,
                                "上传失败，请重试！"
                        );
                        getMessageLabel().setText("暂无任务");
                    }, (currentFile, progress) -> {
                        var index = currentFile.index();
                        var count = currentFile.count();
                        var fileName = currentFile.currentFile().getName();
                        var progressPercentage = progress.getProgressPercentage();
                        log.info(progressPercentage + "% " + fileName + " " + index + "/" + count);
                        rowViewModel.setProgress(progressPercentage);
                    });
                    var shareCode = shareResult.share().getCode();
                    rowViewModel.setShareCode(shareCode);
                    var token = shareResult.editToken();
                    saveUploadHistory(fileName, filePath, shareCode, token);
                    return null;
                }
            };
            worker.execute();
        } else {
            System.err.println("无法获取 JFrame 实例，当前窗口类型为: " + window.getClass().getName());
        }
    }
    @Override
    protected void onOptionalButtonClick() {
        JFrame parentFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
        try {
            UserThemeConfiguration config = YamlConfigurations.update(CONFIG_FILE_PATH, UserThemeConfiguration.class);
            new UploadHistorySelectionDialog(parentFrame, config, selectedHistory -> {
                new MessageInputDialog(parentFrame, selectedHistory, (history, userMessage) -> {
                    try {
                        var api = new MessageControllerApi(ApiHelper.newApiClient());
                        api.addMessage(history.getShareCode(), history.getEditToken(), userMessage);
                        history.addMessage(userMessage);
                        YamlConfigurations.save(CONFIG_FILE_PATH, UserThemeConfiguration.class, config);
                        log.info("用户更新了上传记录消息: 文件名={} 消息={}", history.getFileName(), userMessage);
                        var rowViewModel = new UploadTableRowViewModel(history.getFileName(), "消息已更新", 100, history.getShareCode(), userMessage);
                        addTask(rowViewModel);
                    } catch (Exception e) {
                        log.error("保存上传记录时发生错误", e);
                        JOptionPane.showMessageDialog(this, "保存记录时发生错误！", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }).setVisible(true);
            }).setVisible(true);
        } catch (Exception e) {
            log.error("加载上传历史记录时发生错误", e);
            JOptionPane.showMessageDialog(this, "加载历史记录时发生错误！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    private void saveUploadHistory(String fileName, String filePath, String shareCode, String token) {
        try {
            UserThemeConfiguration config = YamlConfigurations.update(CONFIG_FILE_PATH, UserThemeConfiguration.class);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String uploadDate = dateFormat.format(new Date());
            UserThemeConfiguration.UploadHistory history = new UserThemeConfiguration.UploadHistory(fileName, filePath, uploadDate, shareCode,
                    "", token);
            config.getUploadHistory().add(history);
            YamlConfigurations.save(CONFIG_FILE_PATH, UserThemeConfiguration.class, config);
            log.info("上传历史记录已保存: 文件名={}, 路径={}, 日期={}, 分享码={}", fileName, filePath, uploadDate, shareCode);
        } catch (Exception e) {
            log.error("保存上传历史记录时发生错误", e);
        }
    }
    private void loadUploadHistory() {
        try {
            UserThemeConfiguration config = YamlConfigurations.update(CONFIG_FILE_PATH, UserThemeConfiguration.class);
            for (UserThemeConfiguration.UploadHistory history : config.getUploadHistory()) {
                log.info("加载历史记录: 文件名={}, 路径={}, 日期={}, 分享码={}", history.getFileName(), history.getFilePath(), history.getUploadDate(), history.getShareCode());
                var rowViewModel = new UploadTableRowViewModel(history.getFileName(), "已完成", 100, history.getShareCode(), history.getMessage());
                addTask(rowViewModel);
            }
        } catch (Exception e) {
            log.error("加载上传历史记录时发生错误", e);
        }
    }
}
